﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System;
using Microsoft.Phone.Controls;
using System.Diagnostics; 
using System.Device.Location;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using Microsoft.Phone.Shell;
using System.Windows.Threading;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Threading;
using System.IO;
namespace SpeedRun
{
    public partial class MainPage : PhoneApplicationPage
    {
        GeoCoordinateWatcher geo;
        System.DateTimeOffset OldOffset;
        GeoPositionStatus currentStatus { get; set; }
        double currentSpeedVar
        {
            get
            {
                if (currentSpeed.Text == String.Empty || currentSpeed.Text == null)
                {
                    return 0;
                }
                else
                    return Convert.ToDouble(currentSpeed.Text);
            }
            set
            {
                if (value != null && value != double.NaN)
                {
                    currentSpeed.Text = value.ToString();
                }
                else
                    currentSpeed.Text = "0";
            }
        }
        double currentAltitueVar
        {
            get
            {
                if (currentAltitude.Text == String.Empty || currentAltitude.Text == null)
                {
                    return 0;
                }
                else
                    return Convert.ToDouble(currentAltitude.Text);
            }
            set
            {
                if (value > 0)
                {
                    currentAltitude.Text = value.ToString();
                }
                else
                    currentAltitude.Text = "0";
            }
        }
        DispatcherTimer timer = new DispatcherTimer();
        TimeSpan stopwatchTime;
        Stopwatch stopWatch;
        long dd = 0, hh = 0, mm = 0, ss = 0, ms = 0;
        List<double> speedAnalysis = new List<double>();
        // Constructor
        Thread t;
        public MainPage()
        {
            #region Crappy stuff
            // Check if 'allow' setting already set
            bool? allow = null;
            if (PhoneApplicationService.Current.State.ContainsKey("allow"))
            {
                allow = (bool)PhoneApplicationService.Current.State["allow"];
            }

            if (allow == null)
            {
                // 'allow' setting not set yet (i.e. it is first page load)
                // Display the confirmation question
                var result = MessageBox.Show(
                               "This application uses your location. Do you wish " +
                               "to give it permission to use your location?",
                               "User Location Data",
                               MessageBoxButton.OKCancel);

                // Save answer so you can access it on other pages 
                allow = (result == MessageBoxResult.OK);
                PhoneApplicationService.Current.State["allow"] = allow;
            }

            if (allow.Value)
            {
                // Initiate your app normally
            }
            else
            {
                new Game().Exit();
            }

            #endregion
            
            t = new Thread(new ThreadStart(target));           
          
            stopWatch = new Stopwatch();
            InitializeComponent();
            OldOffset = new System.DateTimeOffset();
            stopwatchTime = new System.TimeSpan();
            try
            {
                geo = new GeoCoordinateWatcher();
                geo.PositionChanged += new System.EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(geo_PositionChanged);
                geo.StatusChanged += new System.EventHandler<GeoPositionStatusChangedEventArgs>(geo_StatusChanged);
                geo.TryStart(true, TimeSpan.FromMilliseconds(100));
                geo.MovementThreshold = 0.000001;
                progressBar.Visibility = System.Windows.Visibility.Visible;
            }
            catch (Exception __e)
            {
                MessageBox.Show("Your App does not have GPS! This app will not run on this Phone!");
                new Game().Exit();
            }

            timer.Interval = TimeSpan.FromMilliseconds(50);
            timer.Tick += new System.EventHandler(timer_Tick);
        }

        void target()
        {
            {
                ProgressBar pb = null;
                Dispatcher.BeginInvoke(() =>
                   {
                       pb = new ProgressBar()
                            {
                                IsIndeterminate = true
                            };

                       pb.Visibility
                            = System.Windows.Visibility.Visible;
                   });

                List<Run> historyRuns = new List<Run>();

                historyRuns = Run.RetrieveHistory();

                historyRuns.Sort(Run.comp);

                try
                {
                    var hist = historyRuns.LastOrDefault();
                    Dispatcher.BeginInvoke(() =>
                    {

                        try
                        {
                            historyTime.Text = hist.time.Minutes.ToString() + " mins";
                            historyCal.Text = hist.calories + " KCalories";
                            historyDistance.Text = hist.distance + " meters";
                            historyType.Text = hist.runType.ToString();
                            HistortTimeStamp.Text = hist.TimeStamp.ToString();
                            total.Text = (historyRuns.Count + 1).ToString();
                            pb.Visibility
                              = System.Windows.Visibility.Collapsed;
                        }
                        catch (Exception ___E)
                        { }
                    });
                }
                catch (Exception _e)
                {

                }
            }

        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if ((App.Current as App).currentRunType != RunTypes.None)
            {
                
            }
            else
            {

            }
            base.OnNavigatedTo(e);
        }


        void timer_Tick(object sender, System.EventArgs e)
        {
            ms = stopWatch.ElapsedMilliseconds;
            ss = ms / 1000;
            ms = ms % 1000;
            mm = ss / 60;
            ss = ss % 60;
            dd = hh / 24;
            hh = hh % 24;
            Dispatcher.BeginInvoke(() =>
                {
                    //time.Text = hh + ":" + mm + ":" + ss + ":" + ms;
                }
            );
        }

        void geo_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {

            currentStatus = e.Status;
            switch (e.Status)
            {
                case GeoPositionStatus.Ready: indicator.Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 0, 255, 0));
                    progressBar.Visibility = System.Windows.Visibility.Collapsed;                    
                    break;
                case GeoPositionStatus.Initializing : indicator.Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(100, Microsoft.Xna.Framework.Color.Yellow.R, Microsoft.Xna.Framework.Color.Yellow.G, Microsoft.Xna.Framework.Color.Yellow.B));
                    break;
                case GeoPositionStatus.NoData : indicator.Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 0, 0 ));                    
                    break;
                case GeoPositionStatus.Disabled :  MessageBox.Show("Your App does not have GPS! This app will not run on this Phone!");
                    progressBar.Visibility = System.Windows.Visibility.Collapsed;
                    new Game().Exit();
                    break;
            }

            Dispatcher.BeginInvoke(delegate()
                {
                    statusMsg.Text = e.Status.ToString();
                }
            );
        }

        GeoCoordinate currentLocationCoord = new GeoCoordinate();

        void geo_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            currentLocationCoord = e.Position.Location; 
            if (currentStatus == GeoPositionStatus.Ready)
            {
                currentLocation.Text = e.Position.Location.Latitude.ToString().Remove(4) + "' " + e.Position.Location.Longitude.ToString().Remove(4) + "''";
                currentSpeedVar = e.Position.Location.Speed;
                currentAltitueVar = e.Position.Location.Altitude;
                speedAnalysis.Add(currentSpeedVar);
                alt.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void TitlePanel_Loaded(object sender, RoutedEventArgs e)
        {
            //time.Text = "00:00:00";
        }

        private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

            var img = sender as Image;

            if (img.Name != "Stop")
            {
                SongCollection songs;
                using (MediaLibrary lib = new MediaLibrary())
                {
                    songs = lib.Songs;
                }
                MediaPlayer.Play(songs, new Random().Next(0, songs.Count));
                timer.Start();
                stopWatch.Start();
                //songName.Text = MediaPlayer.Queue.ActiveSong.Name + "\n" + MediaPlayer.Queue.ActiveSong.Artist;

                //Stop.Visibility = System.Windows.Visibility.Visible;
                //playImage.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                timer.Stop();
                MediaPlayer.Stop();
                stopWatch.Stop();
                double sum = 0;

                foreach (double dble in speedAnalysis)
                {
                    sum += dble;
                }

                sum /= speedAnalysis.Capacity;
                if (sum.ToString() == "NaN" || double.IsNaN(sum))
                {
                    avgSpeed.Text = "0";
                    sum = 0;
                }
                else
                    avgSpeed.Text = sum.ToString().Remove(4);

                TimeSpan ts = new System.TimeSpan((int)dd, (int)hh, (int)mm, (int)ss, (int)ms);
                distance.Text = ((sum * ts.Minutes) > 50 ? (sum * ts.Minutes) : (sum * ts.Seconds)).ToString();

                if (Double.IsNaN(Convert.ToDouble(distance.Text)))
                    distance.Text = "0";

                cal.Text = (Convert.ToDouble(distance.Text) / 60).ToString();
                maxSpeed.Text = speedAnalysis.Max().ToString();

                Process();

                summary.Visibility = System.Windows.Visibility.Visible;
            }

        }

        private void Image_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            timer.Stop();
            MediaPlayer.Pause();
            stopWatch.Stop();

            summary.Visibility = System.Windows.Visibility.Collapsed;
        }


        private void rr_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            MediaPlayer.MovePrevious();
        }

        private void ff_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            MediaPlayer.MoveNext();
            //songName.Text = MediaPlayer.Queue.ActiveSong.Name + "\n" + MediaPlayer.Queue.ActiveSong.Artist;
        }

        private void Image_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            
        }

        private void Image_Hold_1(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new System.Uri("/Profile.xaml", System.UriKind.RelativeOrAbsolute));
        }

        void Process()
        {
        
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            var str = isf.GetFileNames("*.pfk");
            if (str.Length == 0)
            {
               var res = MessageBox.Show("You have not created a Profile. Please create a profile first! Do you want to create it now?","Wait!", MessageBoxButton.OKCancel);
               if (res == MessageBoxResult.OK)
                   NavigationService.Navigate(new System.Uri("/Profile.xaml?id=1", System.UriKind.RelativeOrAbsolute));
               else
                   return;
            }

            NavigationService.Navigate(new System.Uri("/RunType.xaml", System.UriKind.RelativeOrAbsolute));
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new System.Uri("/Profile.xaml?id=3", System.UriKind.RelativeOrAbsolute));
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            var str = isf.GetFileNames("*.pfk");
            if (str.Length == 0)
            {
                var res = MessageBox.Show("You have not created a Profile. Please create a profile first! Do you want to create it now?", "Wait!", MessageBoxButton.OKCancel);
                if (res == MessageBoxResult.OK)
                    NavigationService.Navigate(new System.Uri("/Profile.xaml?id=1", System.UriKind.RelativeOrAbsolute));
                else
                    return;
            }

            NavigationService.Navigate(new System.Uri("/Runner.xaml", System.UriKind.RelativeOrAbsolute));
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
        }

        private void ApplicationBarIconButton_Click(object sender, System.EventArgs e)
        {
            Microsoft.Phone.Tasks.BingMapsTask map = new Microsoft.Phone.Tasks.BingMapsTask();
            map.Center = currentLocationCoord;
            map.ZoomLevel = 1;
            map.Show();

        }

        private void ApplicationBarIconButton_Click_1(object sender, System.EventArgs e)
        {
            Microsoft.Phone.Tasks.BingMapsDirectionsTask dir = new Microsoft.Phone.Tasks.BingMapsDirectionsTask();
            dir.Start = new Microsoft.Phone.Tasks.LabeledMapLocation("Start", currentLocationCoord);
            dir.End = new Microsoft.Phone.Tasks.LabeledMapLocation("End", new GeoCoordinate(currentLocationCoord.Latitude + 0.01, currentLocationCoord.Longitude));
            dir.Show();
        }

        private void PanoramaItem_Loaded(object sender, RoutedEventArgs e)
        {
            if (t.ThreadState == ThreadState.Stopped)
                t = new Thread(target);
            t.Start();
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new System.Uri("/History.xaml", System.UriKind.RelativeOrAbsolute));
        }

        private void ApplicationBarMenuItem_Click(object sender, System.EventArgs e)
        {
            Microsoft.Phone.Tasks.EmailComposeTask email = new Microsoft.Phone.Tasks.EmailComposeTask();
            email.To = @"rushabh.techie@gmail.com";
            email.Subject = @"Feedback";
            email.Show();


        }

        private void ApplicationBarMenuItem_Click_1(object sender, System.EventArgs e)
        {
            Microsoft.Phone.Tasks.MarketplaceReviewTask review = new Microsoft.Phone.Tasks.MarketplaceReviewTask();
            review.Show();
        }

        private void ApplicationBarMenuItem_Click_2(object sender, System.EventArgs e)
        {
            Microsoft.Phone.Tasks.MarketplaceSearchTask search = new Microsoft.Phone.Tasks.MarketplaceSearchTask();
            search.SearchTerms = "Rushabh™";
            search.ContentType = Microsoft.Phone.Tasks.MarketplaceContentType.Applications;
            search.Show();
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            //fadeIn.Begin();
        }

        private void LayoutRoot_Unloaded(object sender, RoutedEventArgs e)
        {
            //fadeIn.Stop();
        }
    }
}